#include "ff_port.h"
#include "drv_sdcard.h"
#include "loger.h"


/* fatfs - SD卡接口 */

/* define */

#define TAG "FS-SD"

/* static func */



static DSTATUS sd_init(void)
{
    drv_sdcard_init();
    // LOG_I(TAG, "sd_init finsh");

    return 0;
}

static DSTATUS sd_deinit(void)
{
    drv_sdcard_deinit();

    return 0;
}

static DSTATUS sd_status(void)
{
    uint8_t sta;

    sta = drv_sdcard_is_exist();
    if (sta != 1) return STA_NODISK;

    return 0;
}

static DRESULT sd_read(BYTE *buff, DWORD sector, UINT count)
{
    uint8_t sta;

    // LOG_D(TAG, "sd_read buff=0x%08X", (uint32_t)buff);
    // sta = drv_sdcard_read_blocks(sector, (uint8_t*)buff, count, FF_FS_TIMEOUT);
    sta = drv_sdcard_read_blocks_dma(sector, (uint32_t*)buff, count);
    if (sta) 
    {
        LOG_E(TAG, "sd_read error", sta);
        return RES_ERROR;
    }
    return RES_OK;
}

static DRESULT sd_write(const BYTE *buff, DWORD sector, UINT count)
{
    uint8_t sta;

    // LOG_I(TAG, "sd_write");
    // sta = drv_sdcard_write_blocks(sector, (uint8_t*)buff, count, FF_FS_TIMEOUT);
    sta = drv_sdcard_write_blocks_dma(sector, (uint32_t*)buff, count);
    if (sta) 
    {
        LOG_E(TAG, "sd_write error %d", sta); 
        return RES_ERROR;
    }

    return RES_OK;
}

static DRESULT sd_ioctl(BYTE cmd, void *buff)
{
    DRESULT res = RES_OK;
    drv_sdcard_info_obj info;

    drv_sdcard_get_card_info(&info);

    switch (cmd)
    {
    case CTRL_SYNC:
        break;
    case GET_SECTOR_COUNT:
        *(DWORD *)buff = info.block_logical_nbr;
        break;
    case GET_SECTOR_SIZE:
        *(DWORD *)buff = 512;
        break;
    case GET_BLOCK_SIZE:
        *(DWORD *)buff = info.block_logical_size;
        break;
    default:
        res = RES_PARERR;
        break;
    }

    return res;
}

/* export */

const _ff_port_opt_t ff_port_sd = 
{
    .name = "sd",
    .init = sd_init,
    .deinit = sd_deinit,
    .status = sd_status,
    .read = sd_read,
    .write = sd_write,
    .ioctl = sd_ioctl,
};

